package com.frxuexi.mynews.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.mynews.intent.NewsTypeIntent
import com.frxuexi.mynews.repository.NewsTypeRepository
import com.frxuexi.mynews.state.NewsTypeState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import java.nio.channels.Channels

class NewsTypeViewModel:ViewModel() {
    val resp by lazy { NewsTypeRepository() }

    val channel= Channel<NewsTypeIntent>(Channel.UNLIMITED)

    private var _state= MutableStateFlow<NewsTypeState>(NewsTypeState.Loading)
    val newsState:StateFlow<NewsTypeState>
        get() = _state

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                if(it==NewsTypeIntent.getNewsType){
                    getNewsType()
                }

            }
        }

    }

    fun getNewsType(){
        viewModelScope.launch {
            resp.getNewsType().collect{
                if(it.code==0){
                    _state.value=NewsTypeState.onSucess(it.data)
                }else{
                    _state.value=NewsTypeState.onError(it.msg)
                }
            }
        }
    }

}